package seqlist.link;

import seqlist.SeqList;

/**
 * @author yuisama
 * @date 2023/03/15 21:28
 * 带头单链表
 **/
public class SingleLinkedListWithHead<E> implements SeqList<E> {
    // 当前单链表一定存在火车头，且不存储具体元素
    private Node dummyHead = new Node(null);
    // 具体的元素个数
    private int size;
    private class Node {
        E val;
        Node next;
        Node(E val) {
            this.val = val;
        }
    }

    public void addFirst(E element) {
        add(0,element);
    }

    @Override
    public void add(E element) {
        add(size,element);
    }

    @Override
    public void add(int index, E element) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("add index illegal!");
        }
        Node prev = dummyHead;
        for (int i = 0; i < index; i++) {
            prev = prev.next;
        }
        Node node = new Node(element);
        node.next = prev.next;
        prev.next = node;
        size ++;
    }

    @Override
    public E removeByIndex(int index) {
        return null;
    }

    @Override
    public void removeByValue(E element) {

    }

    @Override
    public void removeAllValue(E element) {
        // prev一定指向的不是待删除的节点
        Node prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.val.equals(element)) {
                prev.next = prev.next.next;
                size --;
            }else {
                prev = prev.next;
            }
        }
    }

    @Override
    public E set(int index, E element) {
        return null;
    }

    @Override
    public E get(int index) {
        return null;
    }

    @Override
    public boolean contains(E element) {
        return false;
    }

    @Override
    public int indexOf(E element) {
        return 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node x = dummyHead.next;x != null;x = x.next) {
            sb.append(x.val).append("->");
            if (x.next == null) {
                sb.append("NULL");
            }
        }
        return sb.toString();
    }
}